package com.ruoyi.web.controller.system;

import java.util.List;

import com.ruoyi.common.utils.BaseEntityUtils;
import com.ruoyi.common.utils.CollectionUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.future.FutureUtils;
import com.ruoyi.common.validation.group.InsertGroup;
import com.ruoyi.common.validation.group.UpdateGroup;
import com.ruoyi.web.controller.system.mappers.CustomColumnVo;
import com.ruoyi.web.controller.system.mappers.CustomColumnVoMapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import com.ruoyi.common.utils.bean.SelectUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.system.domain.SysCustomColumn;
import com.ruoyi.system.service.ISysCustomColumnService;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.poi.ExcelUtil;
import org.springframework.validation.annotation.Validated;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.validation.group.UpdateBatchGroup;
import com.ruoyi.common.core.domain.StateVo;
import java.util.Collection;
import java.util.stream.Collectors;

/**
 * 用户自定义显示的列Controller
 * 
 * @author ruoyi
 * @date 2022-02-24
 */
@Controller
@RequestMapping("/system/customColumn")
@Slf4j
public class SysCustomColumnController extends BaseController
{
    private String prefix = "system/customColumn";

    @Autowired
    private ISysCustomColumnService sysCustomColumnService;

    @Autowired
    private CustomColumnVoMapper customColumnVoMapper;
    
    @RequiresPermissions("system:customColumn:view")
    @GetMapping()
    public String customColumn()
    {
        return prefix + "/customColumn";
    }

    /**
     * 查询用户自定义显示的列列表
     */
    @RequiresPermissions("system:customColumn:list")
    @GetMapping("/list")
    @ResponseBody
    public TableDataInfo list(SysCustomColumn sysCustomColumn)
    {
        startPage();
        List<SysCustomColumn> list = sysCustomColumnService.selectList(sysCustomColumn);
        return getDataTable(list);
    }

    /**
     * 查询简单的用户自定义显示的列列表 用于select选择器
     */
    @GetMapping("/simpleList")
    @ResponseBody
    public AjaxResult simpleList(SysCustomColumn sysCustomColumn){

        Collection<SysCustomColumn> sysCustomColumnList = sysCustomColumnService.selectSysCustomColumnAllMap().values();

        return AjaxResult.success(SelectUtils.buildSelectList(sysCustomColumnList,SysCustomColumn::getId,SysCustomColumn::getSign));
    }

    /**
     * 获取用户自定义显示的列详细信息
     */
    @RequiresPermissions("system:customColumn:query")
    @GetMapping(value = "/{id}")
    @ResponseBody
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return AjaxResult.success(sysCustomColumnService.selectById(id));
    }

    /**
     * 获取自增排序值
     * @param sysCustomColumn 过滤条件
     * @return
     */
    @GetMapping("/getIncrementWeight")
    @ResponseBody
    public AjaxResult getIncrementWeight(SysCustomColumn sysCustomColumn){
        int weigth = sysCustomColumnService.getMaxOfWeight(sysCustomColumn);
        return AjaxResult.success(++weigth);
    }

    /**
     * 下载用户自定义显示的列导入模板
     */
    @GetMapping("/importTemplate")
    @ResponseBody
    public void importTemplate(HttpServletResponse response)
    {
        ExcelUtil<SysCustomColumn> util = new ExcelUtil<>(SysCustomColumn.class);
        util.importTemplateExcel(response, "用户自定义显示的列数据");
    }

    /**
     * 导入用户自定义显示的列数据
     * @param file 用户自定义显示的列数据文件
     * @param updateSupport 是否为更新
     */
    @Log(title = "用户自定义显示的列", businessType = BusinessType.IMPORT)
    @RequiresPermissions("system:customColumn:import")
    @PostMapping("/importData")
    @ResponseBody
    public AjaxResult importData(MultipartFile file, boolean updateSupport) throws Exception
    {
        ExcelUtil<SysCustomColumn> util = new ExcelUtil<>(SysCustomColumn.class);
        List<SysCustomColumn> sysCustomColumnList = util.importExcel(file.getInputStream());

        if(updateSupport){
            if(sysCustomColumnService.updateBatchById(sysCustomColumnList)){
                return AjaxResult.success("导入用户自定义显示的列数据覆盖成功！");
            }
            return AjaxResult.error("导入用户自定义显示的列数据覆盖失败！");
        }
        if(sysCustomColumnService.insertBatch(sysCustomColumnList)){
            return AjaxResult.success("导入用户自定义显示的列数据新增成功！");
        }
        return AjaxResult.error("导入用户自定义显示的列数据新增失败！");
    }

    /**
     * 导出用户自定义显示的列列表
     */
    @RequiresPermissions("system:customColumn:export")
    @Log(title = "用户自定义显示的列", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    @ResponseBody
    public AjaxResult export(SysCustomColumn sysCustomColumn)
    {
        List<SysCustomColumn> list = sysCustomColumnService.selectList(sysCustomColumn);
        ExcelUtil<SysCustomColumn> util = new ExcelUtil<SysCustomColumn>(SysCustomColumn.class);
        return util.exportExcel(list, "用户自定义显示的列数据");
    }

    /**
     * 新增用户自定义显示的列
     */
    @GetMapping("/add")
    public String add()
    {
        return prefix + "/add";
    }

    /**
     * 新增保存用户自定义显示的列
     */
    @RequiresPermissions("system:customColumn:add")
    @Log(title = "用户自定义显示的列", businessType = BusinessType.INSERT)
    @PostMapping
    @ResponseBody
    public AjaxResult addSave(@Validated(InsertGroup.class) @RequestBody SysCustomColumn sysCustomColumn)
    {
        return toAjax(sysCustomColumnService.insert(sysCustomColumn));
    }

    /***
     * 异步批量新增和 同步返回已保存的列数据列表
     * @param customColumns
     * @return
     */
    @Log(title = "用户自定义显示的列", businessType = BusinessType.INSERT)
    @PostMapping("/batchInsertOrGet")
    @ResponseBody
    public AjaxResult batchInsertOrGet(@Validated(InsertGroup.class) @RequestBody Collection<SysCustomColumn> customColumns){

        String sign = CollectionUtils.getFirst(customColumns).getSign();

        SysCustomColumn params = new SysCustomColumn();
        params.setSign(sign);

        List<SysCustomColumn> sysCustomColumns = sysCustomColumnService.selectSimpleList(params);

        if(StringUtils.isNotEmpty(sysCustomColumns)){

            return AjaxResult.success(customColumnVoMapper.toCustomColumnVoList((List<SysCustomColumn>) BaseEntityUtils.sort(sysCustomColumns)).stream().collect(Collectors.toMap(CustomColumnVo::getField,o->o)));
        }

        FutureUtils.syncExecute(()-> sysCustomColumnService.insertBatch(customColumns))
                .thenAccept(result->{
                    if(result){
                        log.info("saveBatch success for sysCustomColumns:{}!",sysCustomColumns);
                    }else{
                        log.error("saveBatch error for sysCustomColumns:{}!",sysCustomColumns);
                    }
                }).exceptionally(e->{
                    log.error("saveBatch error for sysCustomColumns:{}!",sysCustomColumns);
                    e.printStackTrace();
                    return null;
                });

        return AjaxResult.success();
    }

    /**
     * 修改用户自定义显示的列
     */
    @RequiresPermissions("system:customColumn:edit")
    @GetMapping("/edit/{id}")
    public String edit(@PathVariable("id") Long id, ModelMap mmap)
    {
        SysCustomColumn sysCustomColumn = sysCustomColumnService.selectById(id);
        mmap.put("sysCustomColumn", sysCustomColumn);
        return prefix + "/edit";
    }

    /**
     * 修改保存用户自定义显示的列
     */
    @RequiresPermissions("system:customColumn:edit")
    @Log(title = "用户自定义显示的列", businessType = BusinessType.UPDATE)
    @PutMapping
    @ResponseBody
    public AjaxResult editSave(@Validated(UpdateGroup.class) @RequestBody SysCustomColumn sysCustomColumn)
    {
        String sign = sysCustomColumn.getSign();
        String field = sysCustomColumn.getField();
        sysCustomColumn.setSign(null);
        sysCustomColumn.setField(null);
        if(StringUtils.isNotNull(sysCustomColumn.getId())){
            return toAjax(sysCustomColumnService.updateById(sysCustomColumn));
        }
        return toAjax(sysCustomColumnService.update(sysCustomColumn,
                sysCustomColumnService.lambdaUpdate().eq(SysCustomColumn::getSign,sign)
                .eq(SysCustomColumn::getField,field)));
    }

    /**
     * 修改用户自定义显示的列 状态 根据 ids 主键
     */
    @RequiresPermissions("system:customColumn:edit")
    @Log(title = "用户自定义显示的列", businessType = BusinessType.UPDATE)
    @PutMapping("/updateStateByIds")
    @ResponseBody
    public AjaxResult updateStateByIds(@Validated(value= UpdateBatchGroup.class)@RequestBody StateVo<Long> stateVo)
    {
        return toAjax(sysCustomColumnService.updateStateByIds(stateVo.getIds(),stateVo.getState()));
    }

    /**
     * 删除用户自定义显示的列
     */
    @RequiresPermissions("system:customColumn:remove")
    @Log(title = "用户自定义显示的列", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    @ResponseBody
    public AjaxResult deleteByIds(@PathVariable("ids") List<Long> ids)
    {
            return toAjax(sysCustomColumnService.deleteByIds(ids));
    }
}
